package com.chinacreator.galaxylive.wx;

import com.chinacreator.c2.ioc.ApplicationContextManager;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 网页授权过滤器
 * 默认获取用户信息，配置了snsapi_base 的路径只获取openId
 * ganchao.tang
 */
public class WxWebOauth2Filter implements Filter{

	private final List<String> snsapiBases = new ArrayList<>();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String str = filterConfig.getInitParameter("snsapi_base");
		if(StringUtils.isNotEmpty(str)){
			snsapiBases.addAll(Arrays.asList(str.split(";")));
		}
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		String path = request.getServletPath();
		if(path.contains(".jsp")) {
			WxService wxService = ApplicationContextManager.getContext().getBean(WxService.class);
			WxMpUser wxMpUser = wxService.getWxMpUser(request);
			if (wxMpUser == null) {
				boolean isSnsapiBase = false;
				if (snsapiBases.size() > 0) {
					for (String str : snsapiBases) {
						if (path.startsWith(str)) {
							isSnsapiBase = true;
							break;
						}
					}
				}
				StringBuilder strBackUrl = new StringBuilder();
				strBackUrl.append(request.getScheme())
						.append("://")
						.append(request.getServerName())
						.append(":")
						.append(request.getServerPort())
						.append(request.getContextPath())
						.append(request.getServletPath());
						//.append("?")
						//.append(request.getQueryString());
				String params = request.getQueryString();
				if(null != params && params.indexOf("&") > -1){
					params = params.replace("&", "^");	
				}
				String redirsctURI = String.format(wxService.getWxMpConfigStorage().getOauth2redirectUri(),strBackUrl.toString());
				String url = wxService.oauth2buildAuthorizationUrl(redirsctURI, WxConsts.OAuth2Scope.SNSAPI_USERINFO,params);
				if (isSnsapiBase) {
					url = wxService.oauth2buildAuthorizationUrl(redirsctURI, WxConsts.OAuth2Scope.SNSAPI_BASE, params);
				}
				response.sendRedirect(url);
			}
		}
		chain.doFilter(req,resp);
	}

	@Override
	public void destroy() {

	}


}
